package com.yitiao.simple.chat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;

import java.util.Scanner;

@RequiredArgsConstructor
public class NettyChatClient {

    private final String host;
    private final int port;

    @SneakyThrows
    private void start() {
        NioEventLoopGroup group = new NioEventLoopGroup();

        Bootstrap client = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast("encoder", new StringEncoder())
                                .addLast("decoder", new StringDecoder())
                                .addLast(new NettyChatClientHandler());
                    }
                });

        ChannelFuture channelFuture = client.connect(host, port).sync();
        System.out.println(channelFuture.channel().localAddress());

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            //通过channel 发送到服务器端
            channelFuture.channel().writeAndFlush(msg + "\r\n");
        }
    }

    public static void main(String[] args) {
        new NettyChatClient("localhost", 8801).start();
    }

}
